import React, { useRef, useContext, useEffect } from 'react';
import TableContext from '@root/lib/TableContext';
import HeaderCell from '../HeaderCell';
import useGenStyle from './hooks/useGenStyle';
import getCssPrefix from '@root/lib/getCssPrefix';
const { cssPrefix } = getCssPrefix();
const scrollId = 'header';
function BaseHeader(props) {
    const { columns = [], modifyColumns, type, setMainWidth } = props;
    const headerRef = useRef(null);
    const wrapperRef = useRef(null);
    const { tableState, scrollUtility } = useContext(TableContext);
    const { wrapperStyle, headerStyle } = useGenStyle(columns, type, tableState.scrollToLeft, tableState.scrollToRight);
    useEffect(() => {
        if (type === 'main') {
            scrollUtility.register(scrollId, function (v) {
                let tableWidth = headerRef.current.getBoundingClientRect().width;
                let wrapperWidth = wrapperRef.current.getBoundingClientRect().width;
                let leftValue = v > tableWidth - wrapperWidth ? tableWidth - wrapperWidth : v;
                headerRef.current.style.left = `-${leftValue}px`;
            })

            if (typeof setMainWidth === 'function' && wrapperRef.current) {
                const resizeObserver = new ResizeObserver(() => {
                    let tableWidth = wrapperRef.current.getBoundingClientRect().width;
                    setMainWidth(Math.round(tableWidth * 100) / 100);
                    let wrapperWidth = wrapperRef.current.getBoundingClientRect().width;
                    if (wrapperWidth >= tableWidth) headerRef.current.style.left = 0;
                })
                resizeObserver.observe(wrapperRef.current);
            }
        }
    }, [type])

    return (
        <div className={`${cssPrefix}-base-header_wrapper`} ref={wrapperRef} style={wrapperStyle} >
            <div className={`${cssPrefix}-base-header`} ref={headerRef} style={headerStyle} >
                {
                    columns.map((col) => {
                        return (
                            <HeaderCell key={col.key} column={col} modifyColumns={modifyColumns} type={type}>
                                {col.title}
                            </HeaderCell>
                        );
                    })
                }
            </div>

        </div>
    )
}
export default function Wrapper(props) {
    const { columns = [] } = props;
    if (columns.length === 0) {
        return null;
    } else {
        return <BaseHeader {...props} />
    }
}